package javaStudy.反射;

import javax.swing.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/*
通过反射获取构造方法，并生成对象
 */
public class Demo {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //练习1
        //获取Student的class文件
        Class<Student> studentClass = Student.class;
        //获取Student的无参构造方法
        Constructor<Student> constructor = studentClass.getConstructor();
        //获取Student的有参构造方法
        Constructor<Student> constructor1 = studentClass.getConstructor(String.class, String.class, int.class);
        //通过构造方法创建对象
        Student student = constructor.newInstance();
        Student student1 = constructor1.newInstance("湖海霖", "001", 21);
        System.out.println(student);
        System.out.println(student1);
        System.out.println("=================================");


        //练习2
        //获取私有的构造方法
        Constructor<Student> declaredConstructor = studentClass.getDeclaredConstructor(String.class);
        //反射可以拿到私有的构造方法，但是不可以用来创建对象
        //需要declaredConstructor.setAccessible(true),取消访问检查
        declaredConstructor.setAccessible(true);
        Student student2 = declaredConstructor.newInstance("张艺松");
        System.out.println(student2);
    }

}
